package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"com.opennews.openplatform/payment-api/controller"
	"com.opennews.openplatform/payment-api/nacos"
	"github.com/gin-gonic/gin"
)

var nacosService nacos.NacosService = nacos.NewNacosService()

// Uses gin in main & controller functions only. Because controller is tightly coupled with web framework, here is Gin.
// If we have to switch the framework the main function and controller should be the only place we have to refactor.
// For example, if we use gin.H everywhere that means we have more work to do during such refactoring.
func main() {
	// Default returns an Engine instance with the Logger and Recovery middleware already attached.
	router := gin.Default()

	// Don't trust all proxies.
	// https://pkg.go.dev/github.com/gin-gonic/gin#section-readme
	router.SetTrustedProxies(nil)

	// Generates all controller routes.
	controller.GenerateRoutes(router)

	nacosService.RegisterServiceInstance()
	nacosService.GetConfig()
	nacosService.ListenConfig()

	// makeServiceCall()

	// listens and serves on 0.0.0.0:8080 (for windows "localhost:8080")
	go func() {
		if err := router.Run(":8088"); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal, 1)

	// kill (no param) default send syscanll.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	nacosService.DeregisterServiceInstance()
	nacosService.CancelListenConfig()

	log.Println("Shutdown Server ...")
}

func makeServiceCall() {
	ipAddress, port, _ := nacosService.GetServiceInfo("order-service")

	// Get the service's URL
	serviceURL := fmt.Sprintf("http://%s:%d/api/orders", ipAddress, port)
	fmt.Println("Service URL: ", serviceURL)

	// Make the HTTP GET request
	resp, err := http.Get(serviceURL)

	if err != nil {
		log.Fatalf("Failed to make request: %v", err)
	}

	defer resp.Body.Close()

	// Read the response body
	body, err := io.ReadAll(resp.Body)

	if err != nil {
		log.Fatalf("Failed to read response body: %v", err)
	}

	// Output the response
	fmt.Println("Response:", string(body))
}
